package gov.nhso.prov.acc.apps.acc67;

import gov.nhso.prov.acc.beans.Acc67UserBean;
import gov.nhso.prov.acc.beans.ProvinceBean;
import gov.nhso.prov.acc.core.ConfigBundle;
import gov.nhso.prov.acc.core.DBConnection;
import gov.nhso.prov.acc.utils.Utility;
import gov.nhso.prov.acc.utils.UserInfo;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.isud.core.ISUD;
import com.isud.core.ISUDFactory;

@SuppressWarnings("rawtypes")
public class ACC670000 extends Utility {
	public String url = "/index.jsp";
	
	public ACC670000(HttpServletRequest request, HttpServletResponse response) {
		this.message(request).clearMsg();
		String job = request.getParameter("job");
		if (job.equals("login")) {
			this.login(request);
		} else if (job.equals("repasswd")) {
			this.update(request);
		}
	}
	
	private String login(HttpServletRequest request) {
		
		Connection conn = null;
		ISUD dao = null;
		
		try {
			boolean userActive = false;
			Acc67UserBean userBean = new Acc67UserBean();
			ProvinceBean provinceBean = new ProvinceBean();
			List listUserProvice = new ArrayList();
			String userId = this.getAttr(request, "userId");
			String passwd = this.getAttr(request, "passwd");
			if (!userId.equals("") && !passwd.equals("")) {
				conn = DBConnection.getConnection();
				dao = ISUDFactory.create(conn);
				boolean isAuth = false;
				userBean.setUserId(userId);
				userBean = (Acc67UserBean) dao.select(userBean);
				if (userBean.getActive() != null && userBean.getActive().equals("Y")) {
					if (userBean.getPasswd().equals(dao.encrypt(passwd))) {
						isAuth = true;
					} else if (userBean.getPasswd().equals(passwd) && this.dp.equals("N")) {
						if (!userBean.getCreatedBy().equals("sysencrypt")) {
							Acc67UserBean userSet = new Acc67UserBean();
							userSet.setUserId(userId);
							userSet.setPasswd(dao.encrypt(passwd));
							userSet.setCreatedBy("sysencrypt");
							dao.update(userSet);
							isAuth = true;
						} else if (userBean.getCreatedBy().equals("sysencrypt") && userBean.getPasswd().equals(dao.encrypt(passwd))) {
							isAuth = true;
						}
					} 
				}
				if (isAuth) {
					userActive = true;
					HttpSession session = request.getSession();
					session.setMaxInactiveInterval(60 * 30);
					UserInfo userInfo = new UserInfo();
					dao.copyBeanToBean(userBean, userInfo);
					if (userInfo.getAreaLevel().equals("1")) {
						userInfo.setAreaLevelName(this.properties().areaLevel().get("1"));
						userInfo.setAreaCodeName("");
						userInfo.setAreaDetail(userInfo.getAreaLevelName());
						listUserProvice = dao.selectList(provinceBean," AND NHSO_ZONE NOT IN ('14', '15') ORDER BY NLSSORT(PROVINCE_NAME,'NLS_SORT=THAI_DICTIONARY')");
						userInfo.setListUserProvice(listUserProvice);
					} else if (userInfo.getAreaLevel().equals("2")) {
						userInfo.setAreaLevelName(this.properties().areaLevel().get("2"));
						userInfo.setAreaCodeName(this.dataUtil(dao).getNhsoZoneName(userInfo.getAreaCode()));
						userInfo.setAreaDetail(userInfo.getAreaLevelName() + " - " + userInfo.getAreaCodeName());
						String condition = "";
						condition += " AND PROVINCE_ID IN (SELECT PROVINCE_ID FROM PROVINCE WHERE NHSO_ZONE = '" + userInfo.getAreaCode()+ "' ) ";
						listUserProvice = dao.selectList(provinceBean," "+ condition + " AND NHSO_ZONE NOT IN ('14', '15') ORDER BY NLSSORT(PROVINCE_NAME,'NLS_SORT=THAI_DICTIONARY')");
						userInfo.setListUserProvice(listUserProvice);
					} else if (userInfo.getAreaLevel().equals("3")) {
						userInfo.setAreaLevelName(this.properties().areaLevel().get("3"));
						userInfo.setAreaCodeName(this.dataUtil(dao).getProvinceName(userInfo.getAreaCode()));
						userInfo.setAreaDetail(userInfo.getAreaLevelName() + " - " + userInfo.getAreaCodeName());
						provinceBean.setProvinceId(userInfo.getAreaCode());
						listUserProvice = dao.selectList(provinceBean," AND NHSO_ZONE NOT IN ('14', '15') ORDER BY PROVINCE_NAME");
						userInfo.setListUserProvice(listUserProvice);
					}
					session.setAttribute("userInfo",  userInfo);
					this.sysAuth(request).getMenu(dao, userInfo.getRoleId());
				} else if (userBean.getActive() != null && userBean.getActive().equals("I")){
					userActive = false;
					this.url = "/repasswd.jsp";
				 	request.setAttribute("userId", userId);
				}
				conn.commit();
			}
			if (userActive) {
				this.url = "/apps/index.jsp";
			} else {
			 	request.setAttribute("version", ConfigBundle.getValue("VERSION"));
			 	request.setAttribute("deployDate", ConfigBundle.getValue("DEPLOY_DATE"));
			 	request.setAttribute("deployธรทำ", ConfigBundle.getValue("DEPLOY_TIME"));
				request.setAttribute("loginMsg", "ข้อมูลไม่ถูกต้อง ไม่สามารถเข้าสู่ระบบได้");
			}
		} catch (Exception e) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException eSQL) {
				eSQL.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
				dao = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return this.url;
	}
	private String update(HttpServletRequest request) {
		Connection conn = null;
		ISUD dao = null;
		try {
			conn = DBConnection.getConnection();
			dao = ISUDFactory.create(conn);
			Acc67UserBean userSet = new Acc67UserBean();
			this.beanUtil().copyRequest2Bean(request, userSet);
			userSet.setUserId(userSet.getUserId());
			userSet.setPasswd(dao.encrypt(userSet.getPasswd()));
			userSet.setActive("Y");
			userSet.setUpdatedBy(userSet.getUserId());
			userSet.setUpdatedDate(this.sysDate);
			dao.update(userSet);
			request.setAttribute("userId", userSet.getUserId());
			request.setAttribute("passwd", dao.decrypt(userSet.getPasswd()));
			conn.commit();
		} catch (Exception e) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException eSQL) {
				eSQL.printStackTrace();
			}
			e.printStackTrace();
			
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
				dao = null;
				this.login(request);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return this.url;
	}
}
